package com.qut.atcoder.controller;

import com.qut.atcoder.mappers.UserMapper;
import com.qut.atcoder.pojo.User;
import com.qut.atcoder.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class UserController {
    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired(required = false)
    private UserServiceImpl userServiceImpl;

    //获取所有用户
    @ResponseBody
    @RequestMapping("/getAllUsers")
    public List<User> getAllUsers() {
        return userMapper.selectUser();
    }

    //通过id获取用户
    @ResponseBody
    @RequestMapping("/getUserById")
    public List<User> getUserById(@RequestBody User user) {
        return userMapper.selectUserById(user);
    }

    //通过id删除用户
    //0成功，1失败
    @ResponseBody
    @RequestMapping("/deleteUserById")
    public int deleteUserById(@RequestBody User user) {
        return userServiceImpl.deleteUser(user);
    }
    //用户登录，需要id和密码共同验证
    //用户不存在返回2，密码错误返回1，登录失败返回0
    @ResponseBody
    @RequestMapping("/login")
    public int login(@RequestBody User user) {
        List<User> list = userMapper.selectUserById(user);
        if (list.size() < 1)
            return 2;
        if (!list.get(0).getUser_password().equals(user.getUser_password()))
            return 1;
        //这里可以强化一下规则判断

        return 0;
    }

    //用户注册，密码太短返回1
    @ResponseBody
    @RequestMapping("/register")
    public int register(@RequestBody User user) {
        if (user.getUser_password().length() < 4)
            return 1;
        //其它失败情况返回2

        int ret = userServiceImpl.register(user);
        if (ret == 1)
            return 0;
        return 2;
    }

    @ResponseBody
    @RequestMapping("/editUserById")
    public int editUserById(@RequestBody User user) {
        user.setIs_exist(1);
        return userMapper.updateUserById(user);
    }
}
